<template>
  <view class="background">
    <!-- 搜索框组件 -->
    <view class="my-search" @click="clickSearch">

      <search :bgcolor="'#f5f5f5'"></search>
      <image src="../../static/image/favicon.ico"></image>
    </view>
    <scroll-view class="scrolitem" scroll-x scroll-with-animation enable-flex :scroll-into-view="'scroll'+index">
      <view class="navitem" v-for="(list,i) in  searchlist" :key="i" @click="clickTab(i)" :id="'scroll'+i">
        <view class="navcontent " :class="{active:index===i}">
          {{list}}
        </view>
      </view>
    </scroll-view>
    <!-- 显示部分单曲容器 -->
    <view class="contextContainer" v-if="!isShowAllSingle">
      <view class="singleContainer">
        <view class="single">
          <view class="singletext"> 单曲</view>
        </view>
        <view class="searchContent" v-for="(item,i) in singleSongsList" :key="i">
          <image class="avater" :src="item.al.picUrl"></image>
          <view class="songsname" @click="preserveHistoryRecord">
            <text class="big">{{item.name}}</text>
            <text class="small">{{item.al.name}}</text>
          </view>

        </view>
        <view class="singlebuttom" @click="clicksinglebuttom">
          查看更多{{keywords}}的歌曲
        </view>
      </view>
      <!-- 显示视频 -->
      <view class="singleContainer">
        <view class="single">
          <view class="singletext"> 视频</view>
        </view>
        <view class="videoContainer" v-for="(item,i) in videoList" :key="i">
          <!-- 视频 -->
          <view class="video-box" v-if="item.vid===videoId">
            <video class="video" :id="item.vid" :src="item.url" direction="0" :poster="item.coverUrl"
              @play="handlePlay(event,item.vid)" @timeupdate="update(item.vid,$event)" @ended="endVideo"
              v-if="item.vid===videoId"></video>
          </view>
          <!-- 图片 -->
          <view class="video-box" v-else>
            <image class="video" :src="item.coverUrl" @click="toggle(item.vid)"></image>
          </view>

          <view class="titleContainer">
            <text class="title">{{item.title}}</text>
            <view class="descContainer">

              <text class="desc"> {{item.creator}}</text>
            </view>

          </view>
        </view>
        <view class="singlebuttom" @click="videoButtom">
          查看更多{{keywords}}的视频
        </view>
      </view>
    </view>
    <!-- 显示所以单曲 -->
    <view class="AllcontextContainer" v-else>
      <view class="searchContent" v-for="(item,i) in AllSingle" :key="i">
        <image class="avater" :src="item.album.artist.img1v1Url"></image>
        <view class="songsname" @click="preserveHistoryRecord">
          <text class="big">{{item.name}}</text>
          <text class="small">{{item.artists[0].name}}-{{item.album.name}}</text>
        </view>
      </view>
      <uni-load-more iconType="circle" :status="loadStatus" />
    </view>
  </view>

</template>

<script>
  export default {
    data() {
      return {
        // 导航索引列表
        index: 0,
        searchlist: [],
        // 关键字
        keywords: '',
        // 单曲列表
        singleSongsList: [],
        // 是否显示全部的歌曲
        isShowAllSingle: false,
        // 分页
        pageNum: 0,
        // 视频分页
        videopageNum: 2,
        // 所以单曲
        AllSingle: [],
        // 防抖
        isReachBottom: true,
        // 加载
        loadStatus: 'more',
        // 视频列表
        videoList: [],
        // 视频id
        videoId: '',
        currentTimelist: []
      }
    },
    onLoad(options) {
      // keywords=
      // 1: 单曲, 10: 专辑, 100: 歌手, 1000: 歌单, 1002: 用户, 1004: MV, 1006: 歌词, 1009: 电台, 1014: 视频, 1018:综合
      this.searchlist = ['综合', '单曲', '歌手', '视频', '歌单', '专辑', 'MV', '用户', '歌词', '电台']
      // this.keywords = options.keywords
      this.keywords = '碧莉'
      console.log(this.keywords)
      this.searchSuggust()
      this.getsearchKeyWord(this.keywords)
      // 加载视频接口
      this.getvideoApi()

    },
    onReachBottom() {

      if (this.isShowAllSingle) {
        console.log('下拉触底')

        this.getAllSingle(this.keywords, this.pageNum, 1)
        this.isReachBottom = true
      }
    },
    methods: {
      // 点击更多视频
      videoButtom() {

        uni.navigateTo({
          url: '/subpkg/wxh5previewVideo/wxh5previewVideo?keywords=' + this.keywords
        })
      },
      // 视频结束回调
      endVideo() {
        const Index = this.currentTimelist.findIndex((item => item.videoId === this.videoId))
        console.log(Index)
        this.currentTimelist.splice(Index, 1)
      },
      // 解决多个视频播放
      handlePlay(event, vid) {
        // console.log(event)
        // this.videoId !== vid && this.videoContext && this.videoContext.pause()

        console.log(vid)

        const objlists = this.currentTimelist.find(item => item.videoId === vid)

        if (objlists) {
          console.log(objlists)
          uni.createVideoContext(this.videoId, this).seek(objlists.currentTime)

        }

      },
      // 获取每个视频的进度
      update(vid, event) {
        // console.log(vid)
        let obj = {
          videoId: this.videoId,
          currentTime: event.detail.currentTime
        }
        // console.log(event.detail.currentTime)

        setTimeout(() => {
          const objlist = this.currentTimelist.find(item => item.videoId === obj.videoId)
          if (objlist) {
            objlist.currentTime = obj.currentTime
          } else {

            this.currentTimelist.push(obj)
          }
        }, 3000)

        // console.log(this.currentTimelist)

      },
      // 切换视频就显示那个
      toggle(vid) {
        this.videoId = vid
        // console.log(this.videoId)
      },

      // 获取视频接口
      getvideoApi() {
        this.getsearchApi(this.keywords, this.pageNum, 1014).then(async (res) => {
          console.log(res.result.videos)
          var arrList = [];
          for (const item of res.result.videos) {
            const {
              data: res
            } = await uni.$http.get('/video/url?id=' + item.vid);

            arrList.push({
              coverUrl: item.coverUrl,
              creator: item.creator[0].userName,
              title: item.title,
              url: res.urls[0].url,
              vid: item.vid
            })
          }
          // console.log(arrList)
          this.videoList = arrList
        })
      },
      // 点击导航索引
      clickTab(i) {
        this.index = i
      },
      //获取接口
      async getsearchApi(keyWords, pageNum, type) {
        const {
          data: res
        } = await uni.$http.get('/search?keywords=' + keyWords + '&limit=10' + '&offset=' +
          pageNum * 10 + '&type=' + type)
        return res
      },
      // 获取单曲内容
      getAllSingle(keyWords, pageNum, type) {
        if (this.isReachBottom) {
          // 防抖
          this.isReachBottom = false
          // 把加载图标显示出来
          this.loadStatus = 'loading'
          this.getsearchApi(keyWords, pageNum, type).then(res => {
            console.log(res)
            // 加载图标隐藏

            // console.log(res.result.hasMore)
            if (!res.result.hasMore) {
              // 加载图标隐藏
              this.loadStatus = 'no-more'
              this.pageNum = 1
              return
            }
            this.loadStatus = 'more'
            // 防抖
            this.isReachBottom = true

            // 页数加1
            this.pageNum = this.pageNum + 1
            // 追加数组
            let arrSingle = []
            res.result.songs.forEach(item => arrSingle.push(item))
            this.AllSingle = [...this.AllSingle, ...arrSingle]
            console.log(this.AllSingle)
          })


        }

      },
      // 获取搜索内容
      async getsearchKeyWord(keyWords) {
        const {
          data: res
        } = await uni.$http.get('/cloudsearch?keywords=' + keyWords + '&limit=10')
        console.log(res.result.songs)
        this.singleSongsList = res.result.songs
      },
      // 搜索建议api
      async searchSuggust() {
        const {
          data: res
        } = await uni.$http.get('/search/suggest?keywords=' + this.keywords + '&type=mobile')
        this.keywords = res.result.allMatch[0].keyword
        return res
      },
      // 点击底部更新所以单曲
      clicksinglebuttom() {
        this.index = 1
        this.isShowAllSingle = true
        this.searchSuggust().then(res => {
          // console.log(res.result.allMatch[0].keyword)
          if (res.code !== 200) {
            return uni.$showMsg()
          }
          this.getAllSingle(this.keywords, this.pageNum, 1)
        })

      }

    }
  }
</script>

<style>
  .desc {
    margin-top: 25rpx;
    font-size: 25rpx;
    color: #737373;
  }

  .titleContainer {
    display: flex;
    flex-direction: column;
    width: 50%;
  }

  .descContainer {
    display: flex;
    align-items: center;
  }

  .dscImage {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
  }

  .title {
    font-size: 30rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    /* 设置对齐模式 */
    -webkit-box-orient: vertical;
    /* 设置盒子的行数 */
    -webkit-line-clamp: 2;
  }

  .video-box {
    margin: 15rpx 23rpx;
    padding-bottom: 27%;
    width: 50%;
    position: relative;
  }

  .video {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    object-fit: cover;
    border-radius: 30px;

  }

  .videoContainer {
    display: flex;
    align-items: center;

  }

  .avater {
    width: 70rpx;
    height: 70rpx;
    border-radius: 50%;
  }

  .AllcontextContainer {
    background-color: #fff;
    margin-top: 30rpx;
  }

  .singlebuttom {
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 30rpx;
  }

  .singletext {
    margin-top: 30rpx;
    margin-left: 20rpx;
    font-weight: bold;

  }

  .single {
    flex: 1;
    display: flex;
    align-items: center;
    width: 100vh;
    margin-bottom: 30rpx;
    padding-left: 20rpx;
  }

  /* 搜索 */
  .my-search {
    margin: auto;
    position: relative;
    /* 设置定位效果为“吸顶” */
    position: sticky;
    /* // 吸顶的“位置” */
    top: 0;
    /* // 提高层级，防止被轮播图覆盖 */
    z-index: 999;
    background-color: #f5f5f5 !important;
  }

  .my-search image {
    height: 60rpx;
    width: 60rpx;
    position: absolute;
    right: 32rpx;
    top: 32rpx;

  }

  .background {
    width: 100%;

    background-color: #f5f5f5;
    position: absolute;

  }

  .scrolitem {
    height: 70rpx;
    display: flex;
    white-space: nowrap;

  }

  .navitem {
    padding: 14rpx 10rpx;
    text-align: center;
    line-height: 48rpx;
  }

  .navcontent {
    color: #515151;
    width: 120rpx;
  }

  .active {
    background-color: #ff5252;
    font-weight: bold;
    color: #fff;
    width: 120rpx;
    height: 50rpx;
    border-radius: 30px;

  }

  .singleContainer {
    margin-top: 30rpx;
    background-color: #fff;
    width: 100%;
    border-radius: 30px;
  }

  .contextContainer {
    background-color: #f5f5f5 !important;
    padding: 30rpx 40rpx;

  }



  .searchContent {
    flex: 1;
    display: flex;
    align-items: center;
    width: 100vh;
    height: 120rpx;
    padding-left: 20rpx;
    border-top: 1px solid #eee;
  }

  .songsname {
    display: flex;
    flex-direction: column;
    margin-left: 20rpx;

  }

  .songsname .big {
    font-size: 30rpx;
    margin-bottom: 5rpx;

  }

  .songsname .small {
    font-size: 20rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    /* 设置对齐模式 */
    -webkit-box-orient: vertical;
    /* 设置盒子的行数 */
    -webkit-line-clamp: 1;

  }
</style>
